package com.sinoyd.Code.Until

import android.content.Context
import com.example.sinoyd.frameapplication.KotlinFrame.Dataclass.gson
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.google.gson.JsonArray
import com.google.gson.JsonParser
import com.google.gson.JsonObject
import org.json.JSONObject


/**
 * Created by shenchuanjiang on 2017/2/26.
 *
 *
 * 使用SharedPreferences存取删  数据
 */

object SharedPreferencesFactory {
    //存数据
    fun savedata(context: Context, key: String, info: String) {
        // 1.获得SharedPreferences对象
        val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)// 私有，不能追加
        // 2.获得Editor对象
        val et = sp.edit()
        // 3.存储数据
        et.putString(key, info)
        // 4.提交数据，将数据写在文件
        et.commit()
    }


    /**
     * 保存List
     * @param tag
     * @param datalist
     */
    fun saveclass(context: Context, key: String, jsonstr: String) {
        var preferences = context.getSharedPreferences(key, Context.MODE_PRIVATE)
        var editor = preferences.edit()
        if (jsonstr == "")
            return
        editor.clear()
        editor.putString(key, jsonstr)
        editor.commit()

    }

    /**
     * 获取List
     * @param tag
     * @return
     */
    fun <T> getclass(context: Context, key: String, cls: Class<T>): T? {
        var preferences = context.getSharedPreferences(key, Context.MODE_PRIVATE)
        val strJson = preferences.getString(key, "")
        return if (strJson == "") {
            null
        } else {
            gson.fromJson(strJson, cls)
        }
    }

    //取数据
    fun getdata(context: Context, key: String): String {
        val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
        val token = sp.getString(key, "")
        return if ("" != token) {
            token
        } else {
            ""
        }
    }

    //清除数据
    fun cleardata(context: Context, key: String) {
        val sp = context.getSharedPreferences(key, Context.MODE_PRIVATE)
        sp.edit().clear().commit()
    }
}
